import Vue from 'vue';
import Router from 'vue-router';
import Store from '@/stores';
import Home from './modules/home';
import Login from './modules/login';

Vue.use(Router);

export const defaultRouterMap = [
    ...Home,
    ...Login,
    {
        path: '/404',
        name: '404',
        component: () => import('@/views/error/404')
    },
    {
        path: '*',
        redirect: '/404'
    }
];

const scrollBehavior = (to, from, savedPosition) => {
    if (savedPosition) {
        return savedPosition;
    } else {
        return { x: 0, y: 0 };
    }
};

const createRouter = () =>
    new Router({
        scrollBehavior,
        routes: defaultRouterMap
    });

const router = createRouter();

const whiteList = ['/login', '/404'];

router.beforeEach((to, from, next) => {
    const token = Vue.localStore.get('Token');

    if (to.path === '/login') {
        Store.dispatch('layout/update_loginBeforeRouter', from.path);
    }

    if (whiteList.indexOf(to.path) >= 0) {
        next();
    } else if (!token) {
        next({ path: '/login' });
    } else {
        next();
    }
});

export default router;
